package service

import (
	"comm/dto"
	"comm/entity"
	"core/coreservice"
	"core/corestruct"
	"core/id"
	"core/myerrors"
)

type mainService struct {
}

// List 获取所有通讯端口
func (p *mainService) List(ctx *corestruct.HttpContext) (*[]corestruct.IdNameDto, error) {
	var db = ctx.DB
	db = db.Model(&entity.CommCenter{}).
		Order("id").
		Select("id,name")
	var svr = &coreservice.ListService[corestruct.IdNameDto]{}
	r, err := svr.List(ctx, db)
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}

	return r, nil
}

// Detail 按机构用户详情
func (p *mainService) Detail(mm *corestruct.IdModel, ctx *corestruct.HttpContext) (*dto.CommCenterDto, error) {
	var r = &dto.CommCenterDto{}
	var db = ctx.DB
	db = db.Model(&entity.CommCenter{}).
		Where("id=?", mm.Id).
		Find(r)

	if db.Error != nil {
		return nil, db.Error
	}
	return r, nil
}

// InsertInit 插入初始化
func (p *mainService) InsertInit(ctx *corestruct.HttpContext) (*dto.CommCenterDto, error) {
	var r = &dto.CommCenterDto{
		Id:       id.NewId(),
		Name:     "",
		EndPoint: "",
		Memo:     "",
	}

	return r, nil
}

// CheckExistByEname
// 检查名称是不是存在
func (p *mainService) CheckExistByName(name string, ctx *corestruct.HttpContext) (bool, error) {
	var m = &entity.CommCenter{Name: name}
	tx := ctx.DB.Where(m).
		Select("id").
		//Omit("name").
		Find(m)
	if tx.Error != nil {
		return false, tx.Error
	}
	return m.Id > 0, nil
}

// Insert
// 插入用户
func (p *mainService) Insert(mm *dto.CommCenterDto, ctx *corestruct.HttpContext) (int64, error) {
	bExist, myerr := p.CheckExistByName(mm.Name, ctx)
	if myerr != nil {
		return 0, myerr
	}
	if bExist == true {
		return 0, myerrors.New("名称重复")
	}

	var db = ctx.DB
	tx := coreservice.BaseService.InsertByDto(mm, &entity.CommCenter{}, db)
	if tx.Error != nil {
		return 0, tx.Error
	}

	return mm.Id, nil
}

// Update
// 修改
func (p *mainService) Update(mm *dto.CommCenterDto, ctx *corestruct.HttpContext) (int64, error) {
	var db = ctx.DB

	var m = &entity.CommCenter{
		Id: mm.Id,
	}
	var err = db.Find(m).Error
	if err != nil {
		return 0, myerrors.NewByErr(err)
	}

	if m.Name != mm.Name {
		bExist, myerr := p.CheckExistByName(mm.Name, ctx)
		if myerr != nil {
			return 0, myerr
		}
		if bExist == true {
			return 0, myerrors.New("名称重复")
		}
	}

	tx := coreservice.BaseService.UpdateByDto(mm, &entity.CommCenter{Id: mm.Id}, db)
	if tx.Error != nil {
		return 0, tx.Error
	}

	return mm.Id, nil

}

var (
	MainService = &mainService{}
)
